package com.my.dao;

import com.my.entity.Login;

import java.sql.*;


public class LoginDao {
    public String register(Login login) {
        final String URL="jdbc:mysql://localhost:3306/jsppro";
        final String USERNAME = "root";
        final String PASSWORD = "12345678";
        Connection connection = null;
        PreparedStatement pst = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            String sql = "insert into users values(?,?)";
            pst = connection.prepareStatement(sql);
            pst.setString(1,login.getName());
            pst.setString(2,login.getPwd());
            int count = -1;
            count = pst.executeUpdate();
            if(count>0){
                return "注册成功！";
            }
            return "注册失败！";
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            return "注册失败！";
        }catch (Exception e){
            e.printStackTrace();
            return "注册失败！";
        }finally {
            try{
                if(pst!=null) pst.close();
                if(connection!=null) connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    public static int login(Login login) {
        final String URL="jdbc:mysql://localhost:3306/jsppro";
        final String USERNAME = "root";
        final String PASSWORD = "12345678";
        Connection connection = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            String sql = "select count(*) from users where name=? and pwd=?";
            pst = connection.prepareStatement(sql);
            pst.setString(1,login.getName());
            pst.setString(2,login.getPwd());
            rs = pst.executeQuery();
            int result = -1;
            if(rs.next()){
                result = rs.getInt(1);
            }
            if(result>0){
                return 1;
            }
            return 0;
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            return -1;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }finally {
            try{
                if(rs!=null) rs.close();
                if(pst!=null) pst.close();
                if(connection!=null) connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
